package com.example.se2_funmessages;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.AlertDialog;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.example.se2_funmessages.MainActivity.GetTimeUpdate;


import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SendMessage extends Activity {
	
	Context useThisForToast = this;
	Activity close = this;
	
	int successName = 0;
	private String password = "";
	int userNum;
	String p;
	DatabaseHandler dbh = new DatabaseHandler(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_send_message);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_send_message);
	}

	@Override 
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.send_message, menu);
		return true;
	}
	

	public void send(View v)
	{
		
		

		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Confirmation");
		alert.setMessage("Enter Password");

		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
			p = input.getText().toString();
			EditText nameField = (EditText)findViewById(R.id.nameField);
			
			String usernameToCheck = nameField.getText().toString();
			
			
			
			userNum = dbh.getUserNum();
			
			dbh.close();
			new checkUser().execute(usernameToCheck);
		// Do something with value!
		 }
		});

		 alert.show();

	}
	


public class SendMessageTask extends AsyncTask<Integer, Void, Boolean> {
		
		@Override
		protected Boolean doInBackground(Integer... params) {
			EditText messageTextBox = (EditText)findViewById(R.id.message);

			String message = messageTextBox.getText().toString();
			
			String urlText = "http://softeng.cs.uwosh.edu/students/cs342g3/retrieveMessage.php";
			
			ArrayList<NameValuePair> postParameters;
			
			postParameters = new ArrayList<NameValuePair>();
			
			postParameters.add(new BasicNameValuePair("Header","<?xml version=\"1.0\"?>"));
			postParameters.add(new BasicNameValuePair("beginTo","<userIdTo>"));
			postParameters.add(new BasicNameValuePair("to",params[1]+""));
			postParameters.add(new BasicNameValuePair("endTo","</userIdTo>"));
			postParameters.add(new BasicNameValuePair("beginHeader","<userIdFrom>"));
			postParameters.add(new BasicNameValuePair("from",params[0]+""));
			postParameters.add(new BasicNameValuePair("endHeader","<userIdFrom>"));
			postParameters.add(new BasicNameValuePair("beginPass","<pass>"));
			postParameters.add(new BasicNameValuePair("auth",p));
			postParameters.add(new BasicNameValuePair("endPass","</pass>"));
			postParameters.add(new BasicNameValuePair("beginMessage","<message>"));
			postParameters.add(new BasicNameValuePair("message",message));
			postParameters.add(new BasicNameValuePair("endMessage","</message>"));

			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g3/retrieveMessage.php");
		    try {
				httppost.setEntity(new UrlEncodedFormEntity(postParameters));
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    

		    try {

		        // Execute HTTP Post Request

		        ResponseHandler<String> responseHandler = new BasicResponseHandler();
		        String response = httpclient.execute(httppost, responseHandler).trim();
		        
		        if(Integer.parseInt(response) == 1)
		        {
		        	return true;
		        }
		        else
		        {
		        	return false;
		        }

		        //This is the response from a php application


		    } catch (ClientProtocolException e) {
		        //Toast.makeText(params[0], "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		        //Toast.makeText(params[0], "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
		        // TODO Auto-generated catch block
		    }
			return true;
			
		} // end method doInBackground
		
		@Override
		protected void onPostExecute(Boolean a)
		{
			if(a)
			{
				Toast.makeText(useThisForToast, "Success! message sent", Toast.LENGTH_SHORT).show();				
				close.finish();
			}
			else
			{
				Toast.makeText(useThisForToast, "Failure! message not sent", Toast.LENGTH_SHORT).show();
			}

		} // end method onPostExecute

	}


public class checkUser extends AsyncTask<String, Void, Integer> {
	
	@Override
	protected Integer doInBackground(String... params) {

		
		Log.d("HERE","hereIam");
					
		HttpClient httpclient = new DefaultHttpClient();
		

	    HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g3/checkUser.php?username="+params[0]);
	    

	    try {

	        // Execute HTTP Post Request

	        ResponseHandler<String> responseHandler = new BasicResponseHandler();
	        String response = httpclient.execute(httppost, responseHandler);
	        int intResponse = Integer.parseInt(response);
	       
	        
	        if(intResponse >= 1)
	        {
	        	return intResponse;
	        }
	        else
	        {
	        	return -1;
	        }

	        //This is the response from a php application


	    } catch (ClientProtocolException e) {
	        //Toast.makeText(params[0], "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
	        // TODO Auto-generated catch block
	    } catch (IOException e) {
	        //Toast.makeText(params[0], "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
	        // TODO Auto-generated catch block
	    }
		return -1;
		
	} // end method doInBackground
	
	@Override
	protected void onPostExecute(Integer a)
	{
		if(a >= 1)
		{
			Toast.makeText(useThisForToast, "Success! User exists", Toast.LENGTH_SHORT).show();
			new SendMessageTask().execute(userNum,a);
			

		}
		else
		{
			Toast.makeText(useThisForToast, "Failure user doesn't exist", Toast.LENGTH_SHORT).show();
		}

	} // end method onPostExecute

}
		
}